package com.shop.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shop.bsl.BaseHandler;
import com.shop.bsl.LoginHandler;
import com.shop.dao.DBUtil;

/**
 * Servlet implementation class WebController
 */
@WebServlet("/do")
public class WebController extends HttpServlet {

	public static String ACTION_LOGIN_VIEW = "01";
	public static String ACTION_LOGIN_SUBMIT = "02";
	public static String ACTION_HOME = "03";
	public static String ACTION_CART_VIEW = "04";

	private static final String REQ_PARAM_ACTION = "action";
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public WebController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			processRequest(request, response);
		} catch (Exception exp) {
			request.getRequestDispatcher("/jsp/error.jsp").forward(request,
					response);

		}
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String action = request.getParameter(REQ_PARAM_ACTION);
		Map<String, String[]> requestParm = parseReqeust(request);
		if (ACTION_HOME.equals(action)) {
			request.getRequestDispatcher("/jsp/main.jsp")
					.forward(request, response);
		} else if (ACTION_CART_VIEW.equals(action)) {
			// TODO Forward to handler
		} else if (ACTION_LOGIN_SUBMIT.equals(action)) {
			BaseHandler handler = new LoginHandler();
			Object resp = handler.process(requestParm);

			// TODO Forward to handler
		} else if (ACTION_LOGIN_VIEW.equals(action)) {
			// TODO Forward to handler
		} else {
			request.getRequestDispatcher("/jsp/error.jsp").forward(request,
					response);
		}
	}

	private Map<String, String[]> parseReqeust(HttpServletRequest request) {

		return request.getParameterMap();
	}

	public void destroy() {
		DBUtil.closeConnection();
	}

}
